package com.jxb.demo.websocket;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;

/**
 * @desc netty实现tcp客户端
 */
public class NettyClient {

    public void start() throws InterruptedException{
        //创建eventLoopGroup
        EventLoopGroup boss = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        //设置bootstrap
        bootstrap.group(boss)
                 .remoteAddress("localhost",8080)
                 .channel(NioSocketChannel.class)
                 .option(ChannelOption.TCP_NODELAY,true)
                 .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //记录消息长度编码器
                        pipeline.addLast(new LengthFieldPrepender(2));
                        pipeline.addLast(new MsgPackEncoder());
                        pipeline.addLast(new MsgPackDecoder());
                        pipeline.addLast(new LengthFieldBasedFrameDecoder(65532,0,2,0,2));
                        pipeline.addLast(new NettyClientHandler());
                    }
                 });
        //连接服务端
        ChannelFuture channelFuture = bootstrap.connect().sync();
        channelFuture.channel().closeFuture().sync();
    }

    public static void main(String[] args) {
        try{
            new NettyClient().start();

        }catch (Exception e){

        }


    }

}
